﻿using System;
using System.Text;
using System.Net;
using System.Windows;
using SilverQuery;

namespace SilverQueryDemo.jqia.chapter5
{
	public class EffectsLab : SilverQueryComponent
	{
		public override void ready()
		{
			@q("#controlPanelForm").bind("submit", null, (e) =>
				{
					var effect = @q("#effectsContainer :radio:checked").val();
					object speed = @q("#speedContainer :radio:checked").val();
					
					if ((string)speed == "custom")
					{
						int speedValue;
						if (Int32.TryParse(@q("#speedValueControl").val(), out speedValue))
							speed = speedValue;
						else
							speed = "normal";
					}
					int opacity;
					if (!int.TryParse(@q("#opacityValueControl").val(), out opacity))
						opacity = 100;

					var testSubjects = @q("#testSubjects").children();

					if ((effect == "show" || effect == "hide" || effect == "toggle") && ((speed is string) && (string)speed == "none"))
					{
						showCommand(effect, null, null);

						switch (effect)
						{
							case "show":
								testSubjects.show(); break;
							case "hide":
								testSubjects.hide(); break;
							case "toggle":
								testSubjects.toggle(); break;
						}
					}
					else if (effect == "fadeTo")
					{
						if ((speed is string) && ((string)speed) == "none") speed = "normal";
						showCommand(effect, speed, opacity / (double)100);
						testSubjects.fadeTo(speed.ToString(), opacity / (double)100);
					}
					else
					{
						if ((speed is string) && ((string)speed) == "none") speed = "normal";
						showCommand(effect, speed, null);
						switch (effect)
						{
							case "slideDown":
								testSubjects.slideDown(speed.ToString()); break;
							case "slideUp":
								testSubjects.slideUp(speed.ToString()); break;
							case "slideToggle":
								testSubjects.slideToggle(speed.ToString()); break;
							case "fadeOut":
								testSubjects.fadeOut(speed.ToString()); break;
							case "fadeIn":
								testSubjects.fadeIn(speed.ToString()); break;
						}
					}
					return false;
				});

			@q("#speedContainer").click(e =>
			{
				bool isCustomSpeed = @q("#customSpeedControl").isMatch(":checked");
				q("#speedValueControl").attr("disabled", isCustomSpeed ? "false" : "true");
				return false;
			});
			@q("#testSubject3, #testSubject4").hide();
			@q("testSubject4").css("opacity", "0.5");
		}

		private void showCommand(string effect, object speed, Nullable<double> opacity)
		{
			var text = new StringBuilder();
			text.AppendFormat("$(testSubjects).{0}(", effect);
			if (speed != null)
			{
				bool speedIsString = (speed is string);
				if (speedIsString)
					text.AppendFormat("'{0}'", speed);
				else
					text.Append(speed);
			}

			if (opacity.HasValue)
				text.AppendFormat(",{0}", opacity);
			text.Append(")");

			@q("#appliedCommand").html(text.ToString());
		}
	}
}
